<template>
  <el-dialog

    title="分配角色"
    :visible="showRoleDialog"
    @open="handleOpen"
    @close="handleClose"
  >
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button>取 消</el-button>
      <el-button type="primary" @click="clickSubmit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
// 1.获取所有的角色
// 2.展示当前员工的已有的角色
// 3.重新分配角色
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById } from '@/api/user'
import { reqAssignRole } from '@/api/employee'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleList: [], // 所有的角色
      checkList: [], // 选中的角色

      loading: false
    }
  },
  methods: {
    handleClose() {
    //   this.showRoleDialog = false
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
    },

    handleOpen() {
      this.loading = true
      //   this.getRoleList()
      //   this.getUserDetail()
      //   当两个异步全部执行完毕时,才调用then中的回调函数
      Promise.all([this.getRoleList(), this.getUserDetail()]).then(() => {
        this.loading = false
      })
    },

    // 获取所有的角色列表
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 1000)
      this.roleList = rows
    },

    // 获取员工已有角色
    async getUserDetail() {
      const { data: { roleIds }} = await reqGetUserDetailById(this.userId)
      this.checkList = roleIds || []
    },

    // 重新分配角色
    async clickSubmit() {
      await reqAssignRole({ id: this.userId, roleIds: this.checkList })

      this.$message.success('分配角色成功')
      this.handleClose()
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
